package util;

import java.util.List;

//本类可以将符合条件的json数组转换为where子句，以便于SQL语句的拼接
//适合字符型和数值型字段
public class Condition {
    //字段名
    private String key;
    //操作符
    private String operator;
    //字段值
    private String value;

    public static String toWhereClause(List<Condition>  conditionList){
        //将JSON字串解析为Condition为元素的集合类对象
        //List<Condition> conditionList = JSONArray.parseArray(condition_json,Condition.class);
        //以where开头，注意前后的空格
        StringBuilder sb = new StringBuilder(" where ");
        //将字段名、操作符和字段值依次拼接成字串
        //每个条件后面都附加上“and”，注意前后的空格
        for (Condition c:conditionList){
            sb.append(c.getKey()).append(" ").append(c.getOperator()).append(" ");
            String value = c.getValue();
            //如果操作符是like，自动设置为模糊查询
            if ("like".equalsIgnoreCase(c.getOperator())){
                value = "%" + value + "%";
                //用引号包围value
                value = TxtHelper.quoteMarked(value);
            }
            sb.append(value);
            //注意两端的空格
            sb.append(" and ");
        }
        //把最后一个条件后面的and删除（删除5个字符，包括空格）
        TxtHelper.truncEnding(sb,5);
        return sb.toString();
    }

    public Condition(String key, String operator, String value) {
        this.key = key;
        this.operator = operator;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getOperator() {
        return operator;
    }

    public String getValue() {
        return value;
    }
}
